package org.common.utils.database.access;

import org.common.utils.database.exception.DatabaseException;
import org.common.utils.tool.StringTool;
import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 数据访问管理器
 * @author zhouzhibing
 * @date 2025/4/8
 */
public class DataAccessManager {

    /**
     * 数据源列表<数据源key, 数据访问实例>
     */
    private static final Map<String , DataAccess> DATA_ACCESS_MAP = new ConcurrentHashMap<>();

    private DataAccessManager() {

    }

    /**
     * 注册数据源
     * @param dataKey 数据key
     * @param dataSource 数据源实例
     */
    public static synchronized void register(String dataKey , DataSource dataSource) {
        if(DATA_ACCESS_MAP.containsKey(dataKey)){
            throw new DatabaseException("dataKey = " + dataKey + " already exist");
        }

        DataAccess dataAccess = new DataAccess(dataSource);
        DATA_ACCESS_MAP.put(dataKey , dataAccess);
    }

    /**
     * 判断数据源是否存在
     * @param dataKey 数据源key
     * @return 数据源是否存在
     */
    public static boolean exist(String dataKey) {
        return DATA_ACCESS_MAP.containsKey(dataKey);
    }

    /**
     * 使用
     * @param dataKey 数据key
     * @return 数据访问实例
     */
    public static DataAccess get(String dataKey) {
        if (StringTool.isEmpty(dataKey)) {
            throw new DatabaseException("hashKey = null");
        }

        if(DATA_ACCESS_MAP.isEmpty()) {
            throw new DatabaseException("DATA_SOURCE_MAP.isEmpty()");
        }

        DataAccess dataAccess = DATA_ACCESS_MAP.get(dataKey);
        if(dataAccess == null) {
            throw new DatabaseException("dataSource = null , key:{} not found");
        }
        return dataAccess;
    }
}
